package com.jacobson.huobi.utils

import android.os.Environment
import java.io.*

object SDCardUtil {

    //保存的token文件
    private const val FILE_NAME = "/celueren_token.txt"

    // 向SD卡写入数据
    fun writeSDCard(str: String): Boolean {
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                var sdDir = Environment.getExternalStorageDirectory()
                var outFileStream = FileOutputStream(sdDir.canonicalPath + FILE_NAME)
                outFileStream.write(str.toByteArray())
                outFileStream.close()
                return true
            }else {
                return false
            }
        }catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }

    //读取SD卡数据
    fun readSDCard(): String? {
        var sb = StringBuffer()
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                var sdDir = Environment.getExternalStorageDirectory()
                var file = File(sdDir.canonicalPath + FILE_NAME)

                if (file.exists()) {
                    var inFileStream = FileInputStream(file)
                    var br = BufferedReader(InputStreamReader(inFileStream))
                    var str: String? = ""
                    while (true) {
                        str = br.readLine()
                        if (str.isNullOrEmpty()) {
                            break
                        }else
                            sb.append(str)
                    }
                    return sb.toString()
                }else {
                    return null
                }
            }else {
                return null
            }
        }catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }
}